﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using Devfw.OpenAuth;

namespace Devfw.OpenAuth.Platform
{
    public class SinaV2 : Provider20Base
    {
        public SinaV2(string apiKey, string secretKey)
            : base(apiKey, secretKey)
        { }
        public SinaV2(string apiKey, string secretKey, string accessToken, string refreshToken)
            : base(apiKey, secretKey, accessToken, refreshToken)
        {
        }

        #region 认证

        public string CallBackUrl = "http://127.0.0.1:8001/SinaCallback.aspx";
        private const string authorizeUrl = "https://api.weibo.com/oauth2/authorize";
        private const string accesstokenUrl = "https://api.weibo.com/oauth2/access_token";


        public override string authorize()
        {
            //string query = string.Format("response_type=code&client_id={0}&redirect_uri={1}&state={2}", APIKey, HttpUtility.UrlEncode(CallBackUrl), HttpUtility.UrlEncode(state))
            //return OpenAuthHelper.WebRequest(HttpWebMethod.POST, OpenAuthHelper.CombinUrl(authorizeUrl, query), string.Empty, string.Empty);
            return string.Empty;
        }


        /*public string GetAuthorizeUrl(string state)
        {
            string query = string.Format("response_type=code&client_id={0}&redirect_uri={1}&state={2}", APIKey, HttpUtility.UrlEncode(CallBackUrl), HttpUtility.UrlEncode(state));
            return OpenAuthHelper.CombinUrl(authorizeUrl, query);
        }*/

        public string GetAuthorizeUrl( string callbackUrl = "", string state = "" )
        {
            string query = string.Format("response_type=code&client_id={0}&redirect_uri={1}&state={2}", APIKey, HttpUtility.UrlEncode(callbackUrl), HttpUtility.UrlEncode(state));
            return OpenAuthHelper.CombinUrl(authorizeUrl, query);
        }

        public override string getAccessToken(string s, string s2)
        {
            return getAccessToken(s, s2, "");
        }

        public string getAccessToken(string authorization_code, string callbackUrl = "", string state = "")
        {
            string query = string.Format("grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&state={4}", authorization_code, APIKey, SecretKey, HttpUtility.UrlEncode(callbackUrl), HttpUtility.UrlEncode(state));
            string response = OpenAuthHelper.WebRequest(HttpWebMethod.POST, OpenAuthHelper.CombinUrl(accesstokenUrl, query), string.Empty, string.Empty);

            return response;
        }

        public override string getRefreshToken()
        {
            string query = string.Format("grant_type=refresh_token&refresh_token={0}&client_id={1}&client_secret={2}", RefreshToken, APIKey, SecretKey);
            string response = OpenAuthHelper.WebRequest(HttpWebMethod.POST, OpenAuthHelper.CombinUrl(accesstokenUrl, query), string.Empty, string.Empty);
            return response;
        }

    
        #endregion 认证
        
        #region 转发微博
        /// <summary>
        /// 转发微博
        /// </summary>
        /// <param name="id">微博id</param>
        /// <param name="status">添加的评论</param>
        /// <param name="is_comment">是否在转发的同时发表评论。0表示不发表评论，1表示发表评论给当前微博，2表示发表评论给原微博，3是1、2都发表。默认为0。</param>
        /// <returns></returns>
        public string StatusesRepost(string id, string status, string is_comment)
        {

            string response = WebRequest(HttpWebMethod.POST, "https://api.weibo.com/2/statuses/repost.json",
                new ParameterCollection()
                {
                    new Parameter( "status",  status , ParameterType.Post ),
                    new Parameter( "id", id, ParameterType.Get ),
                    new Parameter( "is_comment", is_comment, ParameterType.Get )
                });

            return response;
        }
        #endregion

        public string getUserShow(string id, string screen_name)
        {
            string response = WebRequest(HttpWebMethod.GET, string.Format("https://api.weibo.com/2/users/show.json"),
                string.IsNullOrWhiteSpace(id)?
                new ParameterCollection()
                {
                    new Parameter( "screen_name",screen_name, ParameterType.Get )
                }
                :
                 new ParameterCollection()
                {
                    new Parameter( "uid",id, ParameterType.Get )
                }
                );

            return response;
        }


        #region 评论微博
        /// <summary>
        /// 评论微博
        /// </summary>
        /// <param name="format"></param>
        /// <param name="id">要评论的微博消息ID</param>
        /// <param name="comment">评论内容。必须做URLEncode,信息内容不超过140个汉字。</param>
        /// <param name="commentOri">当评论一条转发微博时，是否评论给原微博。0:不评论给原微博。1：评论给原微博。默认0.</param>
        /// <returns></returns>
        public string StatusesComment(string id, string comment, string commentOri)
        {
            string response = WebRequest(HttpWebMethod.POST, "https://api.weibo.com/2/comments/create.json",
                new ParameterCollection()
                {
                    new Parameter( "comment", HttpUtility.UrlEncode( comment ), ParameterType.Post ),
                    new Parameter( "id", id, ParameterType.Get ),
                    new Parameter( "comment_ori", commentOri, ParameterType.Get )
                });
            return response;
        }
        #endregion

        #region 获取微博信息
        public string statuses_get(string blogID)
        {
            string response = WebRequest(HttpWebMethod.POST,
                string.Format("https://api.weibo.com/2/statuses/show.json"),
                new ParameterCollection()
                {
                    new Parameter( "id", blogID, ParameterType.Get )
                });

            return response;
        }
        #endregion
        
        #region 发布微博
        public string statuses_update( string status)
        {
            string response = WebRequest(HttpWebMethod.POST, "https://api.weibo.com/2/statuses/update.json",
                new ParameterCollection()
                {
                    new Parameter( "status", HttpUtility.UrlEncode( status ), ParameterType.Post )
                });

            return response;
        }

        public string statuses_upload(string status, byte[] imageByte, string fileName)
        {
            var contentEncoding = "iso-8859-1";
            string fileData = System.Text.Encoding.GetEncoding(contentEncoding).GetString(imageByte);

            string response = WebRequest(HttpWebMethod.POST,"https://upload.api.weibo.com/2/statuses/upload.json",
            new ParameterCollection()
                {
                    new PostParameter( "status", HttpUtility.UrlEncode( status ) ),
                    new PostParameter( "pic", fileData, true,  "filename=\"" + fileName + "\"", false )
                });

            return response;
        }

        public string statuses_upload(string status, string url)
        {
            WebClient client = new WebClient();
            byte[] b = client.DownloadData(url);
            string[] f = url.Split('\\', '/');
            return statuses_upload(status, b, f[f.Length - 1]);
        }
        #endregion

        public string statuses_queryid( string mid, int type = 1, int is_batch = 0, int inbox = 0, int isBase62 = 0)
        {
            string response = WebRequest(HttpWebMethod.GET, "https://api.weibo.com/2/statuses/queryid.json", 
                new ParameterCollection()
                {
                    new Parameter( "mid", HttpUtility.UrlEncode( mid ), ParameterType.Get ),
                    new Parameter( "type", type.ToString(), ParameterType.Get ),
                    new Parameter( "isBase62", isBase62.ToString(), ParameterType.Get )
                });

            return response;
        }

        public string statuses_querymid( string id, int type = 1, int is_batch = 0)
        {
            string response = WebRequest(HttpWebMethod.GET, "https://api.weibo.com/2/statuses/querymid.json",
                new ParameterCollection()
                {
                    new Parameter( "id", HttpUtility.UrlEncode( id ), ParameterType.Get ),
                    new Parameter( "type", type.ToString(), ParameterType.Get ),
                });

            return response;
        }

        public string addFriend(string userID)
        {
            string response = WebRequest(HttpWebMethod.POST, string.Format("https://api.weibo.com/2/friendships/create.json"),
                new ParameterCollection()
                {
                    new Parameter( "uid",userID, ParameterType.Get )
                });

            return response;
        }

        public string WebRequest(HttpWebMethod httpWebMethod ,string url, ParameterCollection collect)
        {
            collect.Add(new Parameter("access_token",AccessToken , ParameterType.Get));
            string querypost = OpenAuthHelper.ToQueryString(collect.GetParameters(ParameterType.Post));
            string queryget   = OpenAuthHelper.ToQueryString( collect.GetParameters(ParameterType.Get));
            string response = string.Empty ;
        
                response = OpenAuthHelper.WebRequest(httpWebMethod, OpenAuthHelper.CombinUrl(url, queryget), querypost, string.Empty);
       
            return response;
        }
  
    }
}
